package com.xxtx.trade.web;

import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

public class DesUtil {


    //3DES
    private static final String algorithm = "DESede";


    //Base64
    private static final Base64.Decoder decoder = Base64.getDecoder();
    private static final Base64.Encoder encoder = Base64.getEncoder();






    public static byte[] Decrypt(String data,String key){
        try {
            //先进行base64解码
            byte[] da = DesUtil.aBase64_decritp(data);
            SecretKey deskey = new SecretKeySpec(creatdeskey(key),algorithm);
            Cipher ch = Cipher.getInstance(algorithm);
            ch.init(Cipher.DECRYPT_MODE, deskey);
            byte[] des = ch.doFinal(da);
            System.out.println("3DES解密获得原报文："+new String(des));
            return des;
        } catch (NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        } catch (NoSuchPaddingException e2) {
            e2.printStackTrace();
        }catch (Exception e3) {
            e3.printStackTrace();
        }
        return null;
    }


    //Base64解码方法
    public static byte[] aBase64_decritp(String encodedText){
        //Base64解碼
        try {
            byte[] textByte = encodedText.getBytes("UTF-8");
            byte[] str = decoder.decode(encodedText);
            System.out.println("Base64解码，得到原始的3DES编码结果："+new String(str));
            //返回解码结果用于3DES解码
            return str;
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //返回解码结果
        return null;

    }

    //Base64编码方法
    public static String aBase64_encript(byte[] textByte){
        String encodedText = encoder.encodeToString(textByte);
        //输出对应编码结果
        System.out.println("Base64编码用于传输，编码结果："+encodedText);

        //把编码结果返回
        //此编码结果已经转化为string型
        return encodedText;
    }



    //把密钥约定为24位
    public static byte[] creatdeskey(String passkey)throws UnsupportedEncodingException {
        byte[] temp = passkey.getBytes();
        byte[] truekey = new byte[24];
        if(temp.length < truekey.length){
            System.arraycopy(temp, 0, truekey, 0, temp.length);
        }
        else{
            System.arraycopy(temp, 0, truekey, 0, truekey.length);
        }
        return truekey;
    }



}
